from flask import url_for
from flask_restful import Resource

from model.crud import QueryOneInstance, UpdateInstance, DeleteInstance, QueryMultipleInstances
from model.tables import Blog, Comment
from restful.data import DataPid, DataContent, DataCid
from restful.error import RenderPostNotExist, RenderCommentNotExist
from restful.request import Get
from restful.response import ResponseSuccess
from restful.session import current_user_required, data, login_required


class CommentOrCancel(Resource):
    @login_required
    @data(DataPid())
    def get(self,data):
        post_comment_data=Get(url_for('postcomment',pid=data['pid'],_external=True))
        return ResponseSuccess(data={
            'comments':post_comment_data,
        })

    @current_user_required
    @data({
        **DataPid(),
        **DataContent()
    })
    def post(self,data,current_user):
        post = QueryOneInstance(Blog, {'id': data['pid']})

        if not post:
            return RenderPostNotExist(data['pid'])

        UpdateInstance(Comment(uid=current_user.id,pid=data['pid'],content=data['content']))
        return ResponseSuccess(msg="评论成功")

    @current_user_required
    @data(DataCid())
    def delete(self,data,current_user):
        comment = QueryOneInstance(Comment,{'id':data['cid'],'uid':current_user.id})

        if not comment:
            return RenderCommentNotExist(data['cid'])

        DeleteInstance(comment)
        return ResponseSuccess("已成功删除评论")